from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection
from decimal import Decimal
from rest_framework.generics import CreateAPIView

# Create your views here.
from goods.models import SKU
from .serializers import CartSKUSerializer, OrderSettlementSerializer, SaveOrderSerializer


class OrderSettlementView(APIView):

    permission_classes = [IsAuthenticated]

    def get(self, request):
        """
        获取订单结算页面
        GET /orders/settlement/
        """
        # 获取用户对象
        user = request.user

        # 从redis中查询购物车
        redis_conn = get_redis_connection('cart')
        sku_count = redis_conn.hgetall('cart_%s' % user.id)
        selected = redis_conn.smembers('cart_selected_%s' % user.id)

        cart = {}
        for sku_id in selected:
            cart[int(sku_id)] = int(sku_count[sku_id])

        # 查询数据库
        skus = SKU.objects.filter(id__in=cart)
        for sku in skus:
            sku.count = cart[sku.id]

        # 运费
        freight = Decimal('10')

        # 序列化返回
        # s = OrderSettlementSerializer({'freight': freight, 'skus': skus})
        # return Response(s.data)

        s = CartSKUSerializer(skus, many=True)
        return Response({'freight': freight, 'skus': s.data})


class SaveOrderView(CreateAPIView):
    """
    保存订单
    POST /orders/
    """
    permission_classes = [IsAuthenticated]
    serializer_class = SaveOrderSerializer




